package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.LogicException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SpotServiceImpl implements ISpotService{


    @Autowired
    private SpotRepository spotRepository;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Spot spot) {
        spot.setId(null);
        spotRepository.save(spot);
    }

    @Override
    public void delete(String id) {
        spotRepository.deleteById(id);
    }

    @Override
    public void update(Spot spot) {
        spotRepository.save(spot);
    }

    @Override
    public Spot get(String id) {
        Spot spot = spotRepository.findById(id).get();
        return spot;
    }

    @Override
    public List<Spot> list() {

        return spotRepository.findAll();
    }

    @Override
    public Page<Spot> queryPageList(SpotQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        return DBHelper.query(template,Spot.class,query,pageable);
    }



    @Override
    public Spot getContentById(String id) {
        Spot spot = spotRepository.findById(id).get();
        return spot;
    }

    @Override
    public void saveOrUpdate(Spot spot) {
        Destination destination = destinationService.get(spot.getDestId());
        spot.setDestName(destination.getName());
        spot.setLastUpdateTime(new Date());
        if(StringUtils.hasLength(spot.getId())){
            spot.setReleaseTime(spot.getReleaseTime());
            this.update(spot);
        }else{
            spot.setCreateTime(new Date());
            this.save(spot);
        }
    }


}
